﻿using System;
using System.Diagnostics;

namespace RemoteWorker.Worker
{
    public class Worker : IWorker
    {
        public string Name { get; set; }

        public void Execute(string fileName, string args)
        {
            Process process = new Process();

            process.StartInfo.FileName = fileName;
            process.StartInfo.Arguments = args;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.EnableRaisingEvents = true;
            process.OutputDataReceived += _OnOutputDataReceived;
            process.Exited += _OnProcess_Exited;

            process.Start();
            process.BeginOutputReadLine();
        }

        public void SetServer(IWorkerServer workerServer)
        {
            _workerServer = workerServer;
        }

        private void _OnOutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            _workerServer.SendOutput(e.Data);
        }

        private void _OnProcess_Exited(object sender, EventArgs e)
        {
            Process process = (Process) sender;
            _workerServer.Complite(process.ExitCode);
        }

        private IWorkerServer _workerServer;
    }
}